const Service = require('egg').Service;

class FollowService extends Service {
    // 关注用户
    async followUser(userId, followId) {
        const { ctx } = this;

        // 检查被关注的用户是否存在
        const targetUser = await ctx.model.User.findByPk(followId);
        if (!targetUser) {
            throw new Error('用户不存在');
        }

        // 检查是否已经关注
        const existingFollow = await ctx.model.Follow.findOne({
            where: {
                user_id: userId,
                follow_id: followId
            }
        });

        if (existingFollow) {
            throw new Error('已经关注该用户');
        }

        // 创建关注关系
        const follow = await ctx.model.Follow.create({
            user_id: userId,
            follow_id: followId,
            created_at: new Date()
        });

        return {
            follow_id: followId,
            user_info: {
                user_id: targetUser.user_id,
                nickname: targetUser.nickname,
                avatar: targetUser.avatar
            }
        };
    }

    // 取消关注
    async unfollowUser(userId, followId) {
        const { ctx } = this;
        const follow = await ctx.model.Follow.findOne({
            where: {
                user_id: userId,
                follow_id: followId
            }
        });

        if (!follow) {
            throw new Error('未关注该用户');
        }

        await follow.destroy();
        return true;
    }

    // 获取关注列表
    async getFollowingList(userId, query = {}) {
        const { ctx } = this;
        const { page = 1, pageSize = 20 } = query;

        const options = {
            where: {
                user_id: userId
            },
            include: [
                {
                    model: ctx.model.User,
                    as: 'followedUser',
                    attributes: ['user_id', 'nickname', 'avatar', 'bio', 'verification_status']
                }
            ],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.Follow.findAndCountAll(options);

        // 处理返回数据
        const followingList = rows.map(follow => ({
            follow_id: follow.follow_id,
            created_at: follow.created_at,
            user: follow.followedUser
        }));

        return {
            list: followingList,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 获取粉丝列表
    async getFollowersList(userId, query = {}) {
        const { ctx } = this;
        const { page = 1, pageSize = 20 } = query;

        const options = {
            where: {
                follow_id: userId
            },
            include: [
                {
                    model: ctx.model.User,
                    as: 'user',
                    attributes: ['user_id', 'nickname', 'avatar', 'bio', 'verification_status']
                }
            ],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.Follow.findAndCountAll(options);

        // 处理返回数据
        const followersList = rows.map(follow => ({
            user_id: follow.user_id,
            created_at: follow.created_at,
            user: follow.user
        }));

        return {
            list: followersList,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 检查是否关注
    async checkFollowing(userId, targetUserId) {
        const { ctx } = this;

        const follow = await ctx.model.Follow.findOne({
            where: {
                user_id: userId,
                follow_id: targetUserId
            }
        });

        return !!follow;
    }

}

module.exports = FollowService;